package com.anonymous.community;

import android.os.Bundle;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.BanUserRequest;
import com.anonymous.community.api.model.GenericResponse;
import com.anonymous.community.api.model.HandleReportRequest;
import com.anonymous.community.api.model.ModeratePostRequest;
import com.anonymous.community.api.model.PendingPostsResponse;
import com.anonymous.community.api.model.ReportListResponse;
import com.anonymous.community.api.model.UserListResponse;
import com.anonymous.community.databinding.ActivityAdminBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.utils.TokenManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 管理员Activity
 * 提供管理员功能入口和常用操作
 */
public class AdminActivity extends BaseActivity {

    private ActivityAdminBinding binding;
    private ApiService apiService;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAdminBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        apiService = ApiClient.getApiService();
        token = TokenManager.getToken(this);

        // 检查管理员权限
        TokenManager tokenManager = new TokenManager(this);
        String role = tokenManager.getUserRole();
        if (!"admin".equals(role) && !"super_admin".equals(role)) {
            Toast.makeText(this, "无管理员权限", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        setupViews();
        loadData();
    }

    private void setupViews() {
        binding.btnBack.setOnClickListener(v -> finish());
        
        // 刷新数据
        binding.swipeRefresh.setOnRefreshListener(() -> loadData());
        binding.swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.black));
    }

    private void loadData() {
        loadPendingPosts();
        loadReports();
        loadUsers();
    }

    /**
     * 加载待审核帖子
     */
    private void loadPendingPosts() {
        apiService.getPendingPosts(token, 1, 10)
                .enqueue(new Callback<PendingPostsResponse>() {
                    @Override
                    public void onResponse(Call<PendingPostsResponse> call, Response<PendingPostsResponse> response) {
                        binding.swipeRefresh.setRefreshing(false);
                        if (response.isSuccessful() && response.body() != null) {
                            int count = response.body().getTotal();
                            binding.tvPendingCount.setText("待审核帖子: " + count);
                        }
                    }

                    @Override
                    public void onFailure(Call<PendingPostsResponse> call, Throwable t) {
                        binding.swipeRefresh.setRefreshing(false);
                    }
                });
    }

    /**
     * 加载举报列表
     */
    private void loadReports() {
        apiService.getCommentReports(token, "pending", 1, 10)
                .enqueue(new Callback<ReportListResponse>() {
                    @Override
                    public void onResponse(Call<ReportListResponse> call, Response<ReportListResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            int count = response.body().getTotal();
                            binding.tvReportCount.setText("待处理举报: " + count);
                        }
                    }

                    @Override
                    public void onFailure(Call<ReportListResponse> call, Throwable t) {
                    }
                });
    }

    /**
     * 加载用户列表
     */
    private void loadUsers() {
        apiService.getAdminUsers(token, 1, 10)
                .enqueue(new Callback<UserListResponse>() {
                    @Override
                    public void onResponse(Call<UserListResponse> call, Response<UserListResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            int count = response.body().getTotal();
                            binding.tvUserCount.setText("用户总数: " + count);
                        }
                    }

                    @Override
                    public void onFailure(Call<UserListResponse> call, Throwable t) {
                    }
                });
    }

    /**
     * 审核帖子示例
     */
    public void moderatePost(int postId, String status, String reason) {
        ModeratePostRequest request = new ModeratePostRequest(status, reason);
        apiService.moderatePost(token, postId, request)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        if (response.isSuccessful()) {
                            Toast.makeText(AdminActivity.this, "审核完成", Toast.LENGTH_SHORT).show();
                            loadPendingPosts();
                        } else {
                            Toast.makeText(AdminActivity.this, "审核失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        Toast.makeText(AdminActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 封禁用户示例
     */
    public void banUser(int userId, boolean ban) {
        BanUserRequest request = new BanUserRequest(!ban);  // is_active = !ban
        apiService.banUser(token, userId, request)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        if (response.isSuccessful()) {
                            String msg = ban ? "用户已封禁" : "用户已解封";
                            Toast.makeText(AdminActivity.this, msg, Toast.LENGTH_SHORT).show();
                            loadUsers();
                        } else {
                            Toast.makeText(AdminActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        Toast.makeText(AdminActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 处理举报示例
     */
    public void handleReport(int reportId, String action, String reason) {
        HandleReportRequest request = new HandleReportRequest(action, reason);
        apiService.handleCommentReport(token, reportId, request)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        if (response.isSuccessful()) {
                            Toast.makeText(AdminActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                            loadReports();
                        } else {
                            Toast.makeText(AdminActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        Toast.makeText(AdminActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "管理员页";
    }
}

